<template>
  <TreeTableLayout>
    <template #tree>
      <Tree @query="doQuery" @gateway="getGateway" :gatewayType="-1"></Tree>
    </template>
    <template #table>
      <RightTableLayout :slotName="['search', 'operation', 'table', 'pagination']">
        <template #search>
          <BaseSearch @querySearch="querySearch" :searchFields="searchFields"></BaseSearch>
        </template>
        <template #operation>
          <el-button v-if="pubGatewayType == 1" v-show="pid" @click="add">
            <el-icon>
              <DocumentAdd />
            </el-icon>
            {{ i18n.fy.新增 + i18n.fy.定时任务 }}</el-button>
          <el-button v-if="pubGatewayType == 0" v-show="pid" @click="add">
            {{ i18n.fy.新增 + i18n.fy.定时任务 }}</el-button>
        </template>
        <template #table>
          <el-table :empty-text="i18n.fy.nodata" :data="data.tableData" height="100%" border v-loading="data.loading"
            :element-loading-text="i18n.fy.loading">
            <el-table-column prop="ruleTitle" :label="i18n.fy.任务名称" />
            <el-table-column prop="startTime" :label="i18n.fy.执行时间" align="center" />
            <el-table-column prop="enableState" :label="i18n.fy.任务状态" align="center">
              <template #default="scope">
                <span :class="'enable-state-cls-' + scope.row.enableState">
                  {{ scope.row.enableState === 1 ? i18n.fy.已启用 : i18n.fy.已停用 }}
                </span>
              </template>
            </el-table-column>
            <el-table-column prop="operateTrigger" :label="i18n.language === 'zh-cn' ? '感应状态' : 'operateTrigger'"
              align="center" width="110">
              <template #default="scope">
                <span :class="'operateTrigger' + scope.row.operateTrigger">
                  {{ showOperate(scope.row.operateTrigger) }}
                </span>
              </template>
            </el-table-column>
            <el-table-column prop="chooseWorkDay" :label="i18n.language === 'zh-cn' ? '运行周期' : 'chooseWorkDay'"
              align="center">
              <template #default="scope">
                <div v-html="showChooseWorkDay(scope.row.chooseWorkDay)"></div>
              </template>
            </el-table-column>
            <el-table-column prop="chooseWorkDay" :label="i18n.language === 'zh-cn' ? '区组' : 'Lampgroup'"
              align="center">
              <template #default="scope">
                <div v-show="scope.row.gatewayType != 'PLC'">
                  <p class="operateInfo" v-for="(item, i) in showOper(scope.row.operateInfo)">
                    {{ item.area }}区
                    <span v-if="item.code != '400'">{{ item.address }}</span>
                    <span v-if="item.code == '200'">组</span>
                    <span v-if="item.code == '300'">标签</span>
                    <span v-if="item.code == '100' || item.code == '10'">号</span>
                  </p>
                </div>
                <div v-html="showLampgroup(scope.row)" v-show="scope.row.gatewayType == 'PLC'">
                </div>
              </template>
            </el-table-column>
            <el-table-column width="100" prop="chooseWorkDay"
              :label="pubGatewayType == 0 ? i18n.fy.brightness : i18n.fy.scene" align="center">
              <template #default="scope">
                <div v-if="pubGatewayType == 1">场景{{ showProfile(scope.row) }}</div>
                <div v-if="pubGatewayType == 0">{{ scope.row.hasPeopleBrightness == undefined ? i18n.fy.无 :
        scope.row.hasPeopleBrightness }}</div>
              </template>
            </el-table-column>
            <el-table-column :label="i18n.fy.操作" width="210" align="center">
              <template #default="scope">
                <el-button type="primary" size="small" :class="scope.row.enableState !== 1 ? 'q-y-cls' : 't-y-cls'"
                  @click="modifyTaskStatus(scope.row)">
                  {{ scope.row.enableState !== 1 ? i18n.fy.启用 : i18n.fy.停用 }}
                </el-button>
                <el-button type="primary" size="small" @click="edit(scope.row)">
                  {{ i18n.fy.编辑 }}
                </el-button>
                <el-button type="danger" size="small" @click="del(scope.row)">
                  {{ i18n.fy.删除 }}
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </template>
        <template #pagination>
          <el-pagination @size-change="onChanSize" @current-change="onChanPage"
            v-model:current-page="data.queryForm.page" v-model:page-size="data.queryForm.pageSize"
            :total="data.total" />
        </template>
      </RightTableLayout>
    </template>
  </TreeTableLayout>
  <el-dialog v-model="lampVisible" draggable :title="i18n.fy.新增灯具" width="40%" class="">
    <div style="padding-bottom: 30px;">
      <div class="top ">
        <el-row>
          <el-col :span="4">
            <el-select clearable style="width:120px;" v-model="typeOpt" class="m-2" placeholder="">
              <el-option v-for="item in typeOptions" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-col>
          <el-col :span="5" v-if='typeOpt != 10'>
            <span>{{ i18n.fy.网关 }}</span>
            <el-select clearable v-model="gateway_1" class="m-2" placeholder="">
              <el-option :label="i18n.fy.allgateways" :value="''" />
              <el-option v-for="item in gatewayList" :key="item.id" :label="item.nickName" :value="item.id" />
            </el-select>
          </el-col>
          <el-col :span="4" v-if='typeOpt != 10'>
            <span>{{ i18n.fy.区 }}}</span>
            <el-select clearable v-model="district_1" :placeholder="i18n.language === 'zh-cn' ? '区' : 'distinguish'">
              <el-option v-for="item in deviceAreaAllList" :value="item.area_code">
                {{ item.area_code }}
              </el-option>
            </el-select>
          </el-col>
          <el-col :span="8" v-if="typeOpt == 200 && typeOpt != 10">
            <span>{{ i18n.fy.组 }}}</span>
            <el-select clearable v-model="group_1" placeholder="" multiple filterable>
              <el-option v-for="item in optionsGroup" :value="item.group_name" v-show="item.group_name != '全部'">
                {{ item.group_name }}
              </el-option>
            </el-select>
          </el-col>
          <el-col :span="4" v-if="typeOpt == 100 && typeOpt != 10">
            <span>{{ i18n.fy.号 }}}</span>
            <el-input v-model="num_1" placeholder="" />
          </el-col>
          <el-col :span="4" v-if="typeOpt == 300 && typeOpt != 10">
            <span>{{ i18n.fy.标签 }}}</span>
            <el-input v-model="num_tag" placeholder="" />
          </el-col>
        </el-row>
      </div>
      <el-table :empty-text="i18n.fy.nodata" v-if='typeOpt == 10' :data="sceneTableDataList" style="height:400px"
        class="sceneTableData" @selection-change="handleSelectionChange3" ref='multipleSelection3Tab'>
        <el-table-column type="selection" width="55" />
        <el-table-column prop="areaCode" :label="i18n.fy.区" />
        <el-table-column prop="groupName" :label="i18n.fy.组">
        </el-table-column>
        <el-table-column prop="deviceIndex" :label="i18n.fy.号">
        </el-table-column>
        <el-table-column prop="ramk" :label="i18n.fy.备注">
        </el-table-column>
        <el-table-column prop="pwd" :label="i18n.fy.网络密码" width="240">
          <template #default="scope">
            <el-input v-model="scope.row.pwd" :placeholder="i18n.fy.请输入 + i18n.fy.网络密码" />
          </template>
        </el-table-column>
      </el-table>
    </div>
    <template #footer>
      <span class="dialog-footer">
        <el-button type="primary" @click="enterOs()">{{ i18n.fy.confirm }}</el-button>
        <el-button @click="lampVisible = false;">{{ i18n.fy.cancel }}</el-button>
      </span>
    </template>
  </el-dialog>
  <div style="display: none;padding: 20px;text-align: center;background:#000;" id="saveOrUpdateDiv99">
    <form class="layui-form" lay-filter="dataFrm67" id="dataFrm67">
      <input type="hidden" class="deviceFid" name="deviceFid">
      <div class="layui-form-item">
        <label class="layui-form-label">
          {{ i18n.fy.任务编号 }}
          :</label>
        <div class="layui-input-block">
          <input type="text" name="ruleTitle" id="ruleTitle" lay-verify="required"
            :placeholder="i18n.fy.请输入 + i18n.fy.任务编号" autocomplete="off" class="layui-input">
        </div>
      </div>
      <div class="layui-form-item">
        <label class="layui-form-label">
          {{ i18n.fy.执行时间 }}
          :</label>
        <div class="layui-input-block">
          <input type="text" name="startTime" id='startTime' lay-verify="required" readonly
            :placeholder="i18n.fy.请选择 + i18n.fy.开始时间" autocomplete="off" class="layui-input">
        </div>
      </div>
      <div class="layui-form-item" style="display:none;">
        <label class="layui-form-label">
          {{ i18n.fy.结束时间 }}
          :</label>
        <div class="layui-input-block">
          <input type="text" name="stopTime" lay-verify="required" id="stopTime" readonly
            :placeholder="i18n.fy.请选择 + i18n.fy.结束时间" autocomplete="off" class="layui-input" value="23:59">
        </div>
      </div>
      <div class="layui-form-item" v-show="pubGatewayType == 0">
        <label class="layui-form-label">
          {{ i18n.language === 'zh-cn' ? "执行亮度" : 'Execute brightness' }}
          :</label>
        <div class="layui-input-block">
          <input type="text" name="hasPeopleBrightness" lay-verify="required" id="hasPeopleBrightness" readonly
            :placeholder="i18n.language === 'zh-cn' ? '请输入亮度' : 'Please enter brightness'" autocomplete="off"
            class="layui-input">
        </div>
      </div>
      <div class="layui-form-item" style="height:0px; overflow: hidden;margin-bottom: 0px;">
        <label class="layui-form-label">
          {{ i18n.language === 'zh-cn' ? "无人时亮度" : 'Brightness when unmanned' }}
          :</label>
        <div class="layui-input-block">
          <input type="text" name="noPeopleBrightness" lay-verify="required" id="noPeopleBrightness" readonly
            :placeholder="i18n.language === 'zh-cn' ? '请输入无人时亮度' : 'Please enter the brightness when there is no one present'"
            autocomplete="off" class="layui-input" value="1">
        </div>
      </div>
      <div class="layui-form-item">
        <label class="layui-form-label">
          {{ i18n.fy.运行周期 }}
          :</label>
        <div class="layui-input-block">
          <el-select v-model="chooseWorkDay" multiple :placeholder="i18n.fy.请选择 + i18n.fy.运行周期" style="width:100%;">
            <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </div>
      </div>
      <div class="layui-form-item" v-if="pubGatewayType == 0">
        <label class="layui-form-label">
          {{ i18n.fy.组名 }}
          :</label>
        <div class="layui-input-block">
          <el-select v-model="customName" multiple :placeholder="i18n.fy.请选择 + i18n.fy.组名" style="width:100%;">
            <el-option v-for="item in optionsGroup" :key="item.group_name" :label="item.name || item.group_name"
              :value="item.group_name" />
          </el-select>
        </div>
      </div>
      <template v-if="pubGatewayType == 1">
        <div style="">
          <div class="layui-form-item">
            <label class="layui-form-label">
              {{ i18n.language === 'zh-cn' ? "操控灯组" : 'Select Block' }}
              :</label>
            <div class="layui-input-block">
              <p class="altconp">
                <span class="altcon" v-for="(item, i) in scenModel.data.operateInfo">
                  {{ item.area }}区
                  <span v-if="item.code != '400'">{{ item.address }}</span>
                  <span v-if="item.code == '200'">组</span>
                  <span v-if="item.code == '300'">标签</span>
                  <span v-if="item.code == '100' || item.code == '10'">号</span>
                  <el-icon @click="deleteTag(i)">
                    <Close />
                  </el-icon>
                </span>
                <el-button style="margin-left:5px;" type="primary" @click="addingLamp()">新增灯</el-button>
              </p>
            </div>
          </div>
        </div>
        <div class="layui-form-item">
          <label class="layui-form-label">
            {{ i18n.language === 'zh-cn' ? "调用情景" : 'Call scenario' }}
            :</label>
          <div class="layui-input-block">
            <el-select style="width:100%" v-model="transferScene" class="m-2" placeholder="">
              <el-option v-for="item in sceneOptions" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </div>
        </div>
      </template>
      <div class="layui-form-item">
        <div class="layui-inline" style="float: left;">
          <label class="layui-form-label">
            {{ i18n.language === 'zh-cn' ? "任务状态" : 'Status' }}
            :</label>
          <div class="layui-input-inline">
            <input type="radio" id="status_0" name="enableState" value="1" checked="checked" :title="i18n.fy.启用">
            <input type="radio" id='status_1' name="enableState" value="0" :title="i18n.fy.不启用">
          </div>
        </div>
        <div class="layui-inline" style="float: left;">
          <label class="layui-form-label">
            {{ i18n.fy.感应状态 }}
            :</label>
          <div class="layui-input-inline">
            <input type="radio" id="status_3" name="operateTrigger" value="1" :title="i18n.fy.启用">
            <input type="radio" id="status_4" name="operateTrigger" value="0" checked="checked" :title="i18n.fy.不启用">
          </div>
        </div>
      </div>
      <div class="layui-form-item" style="text-align: center;padding-top: 10px;">
        <div class="layui-input-block">
          <button type="button" class="layui-btn layui-btn-normal layui-btn-sm layui-icon layui-icon-release"
            lay-filter="doSubmit66" id="doSubmit99" @click="doSubmit()">
            {{ i18n.fy.提交 }}
          </button>
        </div>
      </div>
    </form>
  </div>
  <div id="slideDiv" style="display: none;padding: 20px;text-align: center">
    <div id="slideTest1"></div>
  </div>
  <div id="slideDiv2" style="display: none;padding: 20px;text-align: center">
    <div id="slideTest2"></div>
  </div>
</template>

<script setup>
defineOptions({ name: 'TimingRuleList' })
import RightTableLayout from "@/views/workbench/components/RightTableLayout.vue";
import TreeTableLayout from "@/views/workbench/components/TreeTableLayout.vue";
import BaseSearch from '@/views/workbench/components/BaseSearch.vue'
// import Tree from '@/views/workbench/components/tree.vue'
import Tree from '@/components/tree.vue'
import { getAllDeviceTimingList, upStateTimingInterface } from "@/api/wirelessmanageApi";
import { i18nStore } from "@/pinia/i18n";
const i18n = i18nStore();
const { appContext: { config: { globalProperties } } } = getCurrentInstance()
let $httpUrl = globalProperties.$httpUrl;

let searchFields = reactive([{ key: 'ruleTitle', label: i18n.fy.任务名称, val: '' }])
let searchVal = reactive({})
let chooseWorkDay = ref([]);
let options = ref([
  { value: 1, label: "周一" },
  { value: 2, label: "周二" },
  { value: 3, label: "周三" },
  { value: 4, label: "周四" },
  { value: 5, label: "周五" },
  { value: 6, label: "周六" },
  { value: 7, label: "周日" },
])
let gateway_1 = ref('');
let num_1 = ref('');
let num_tag = ref('');
let tags = ref([]);
let multipleSelection3Tab = ref(null);
let data = reactive({ queryForm: { pageNum: 1, pageSize: 20 }, tableData: [], total: 0, dialog: false, form: {}, rules: {} })

// 搜索查询
const querySearch = (obj) => {
  data.queryForm.pageNum = 1
  data.queryForm.pageSize = 20
  searchVal.value = obj;
  getTableData();
}
// 修改分页数
const onChanSize = (e) => {
  data.queryForm.pageNum = 1;
  data.queryForm.pageSize = e;
  getTableData();
}
// 修改分页
const onChanPage = (e) => {
  data.queryForm.pageNum = e;
  getTableData();
}
// 获取表格数据
const getTableData = async () => {
  let proms = {
    ...data.queryForm,
    ...searchVal.value,
    deviceFid: pid.value
  }
  data.dialog = true
  const res = await getAllDeviceTimingList(proms)
  console.log('定时任务列表->', res);
  if (Array.isArray(res.content)) {
    res.content.forEach(element => {
      element.operateInfoStr = element.operateInfo
      element.operateInfoObj = JSON.parse(element.operateInfo)
    });
    data.tableData = res.content;
    data.total = res.totalElements;
    data.dialog = false
  }
}
// 状态更新操作(0：停用、1：启用)
const modifyTaskStatus = async (row) => {
  data.dialog = true
  if (!row.enableState) { row.enableState = 0 }
  row.enableState === 0 ? row.enableState = 1 : row.enableState = 0
  const res = await upStateTimingInterface(row, row.enableState)
  if (res.code == 200) {
    ElMessage.success(`定时任务状态更新${res.message}`);
    getTableData();
  } else {
    ElMessage.error(res.message);
  }
}
// 重置查询表单
const reQueryForm = () => {
  data.queryForm = {
    page: 1,
    limit: 100
  }
}
// 新增
const add = () => {
  scenModel.data.operateInfo = [];
  group_1.value = [];
  district_1.value = '';
  transferScene.value = '';
  curData = null;
  form.render();
  chooseWorkDay.value = [];
  mainIndex = layer.open({
    type: 1,
    title: i18n.language === 'zh-cn' ? '新增定时任务' : 'Add scheduled tasks',
    content: $("#saveOrUpdateDiv99"),
    area: ['37%', '55%'],
    maxmin: true,
    success: function (index) {
      $("#ruleTitle").val('');
      $("#startTime").val('');
      $("#stopTime").val('');
      $("#hasPeopleBrightness").val('');
      customName.value = '';
      if (pubGatewayType.value == 1) {
        url = $httpUrl + "/deviceTimingRule/addMeshTimingRule";
      } else {
        url = $httpUrl + "/deviceTimingRule/addTimingRule";
      }
    }
  });
}

let formRef = ref(null)

const submit = () => { // 提交新增/编辑表单
  formRef.value.validate(valid => {
    if (valid) {

    }
  })
}

let pid = ref('');
let pubGatewayType = ref('');
const doQuery = (params) => {
  console.log('doQuery->', params);
  pubGatewayType.value = params.gatewayType ? 1 : 0;
  console.log("pubGatewayType.value", pubGatewayType.value);
  console.log('pubGatewayType.value', pubGatewayType.value);
  if (params.deviceFid) {
    pid.value = params.deviceFid
  }
  getDeviceAliasAllList();
  getTableData(params);
  getDeviceAreaAllList();
}
let sceneOptions = ref([{ value: 1, label: "场景1" }, { value: 2, label: "场景2" }, { value: 3, label: "场景3" }, { value: 4, label: "场景4" }, { value: 5, label: "场景5" }, { value: 6, label: "场景6" }, { value: 7, label: "场景7" }, { value: 8, label: "场景8" }, { value: 9, label: "场景9" },
{ value: 10, label: "场景10" }, { value: 11, label: "场景11" }, { value: 12, label: "场景12" }
])
let sceneTableDataList = ref([]);
const getList3 = (params, num) => { // 获取表格数据
  if (params.groupName == '全部') {
    delete params.groupName;
  }
  $axios.get('/operationDevice/queryOperationDeviceAllList', {
    ...data.queryForm,
    ...params,
    deviceFid: pid.value,
    gatewayType: 1,
    limit: 10000,
    page: 1
  }).then(res => {
    if (res.data.data == null) {
      data.loading = false;
      return;
    }
    for (let i = 0; i < res.data.data.records.length; i++) {
      if (res.data.data.records[i].areaCode) {
        res.data.data.records[i].areaCodeLabel = hex2int(res.data.data.records[i].areaCode.replace(/\s*/g, ""));
      }
      if (res.data.data.records[i].groupName) {
        res.data.data.records[i].groupNameLabel = hex2int(res.data.data.records[i].groupName.slice(1).replace(/\s*/g, ""));
      }
    }
    res.data.data.records = groupAndSort("groupNameLabel", "areaCodeLabel", res.data.data.records);
    res.data.data.records = res.data.data.records.sort(createComprisonFunction("areaCodeLabel"));
    sceneTableDataList.value = res.data.data.records;
  })
}

const hex2int = (hex) => {
  if (hex == null || hex == '') {
    return;
  }
  var len = hex.length, a = new Array(len), code;
  for (var i = 0; i < len; i++) {
    code = hex.charCodeAt(i);
    if (48 <= code && code < 58) {
      code -= 48;
    } else {
      code = (code & 0xdf) - 65 + 10;
    }
    a[i] = code;
  }

  return a.reduce(function (acc, c) {
    acc = 16 * acc + c;
    return acc;
  }, 0);

};

const groupAndSort = (groupFields, sortFields, list) => {
  if (Array.isArray(list) && list.length <= 0) {
    return []
  }
  let tempList = []
  list = sortByFields(groupFields, list)
  let tempGroupValue = list[0][groupFields]
  for (let i = 0; i < list.length; i++) {
    if (!list[i]) {
      continue
    }
    if (list[i][groupFields] != tempGroupValue) {
      tempGroupValue = list[i][groupFields]
    }
    addObjToList(groupFields, sortFields, tempGroupValue, list[i], tempList)
    list.splice(i, 1);
    i--;
  }
  return tempList
}

const addObjToList = (groupFields, sortFields, tempGroupValue, obj, list) => {
  let tempLength = list.length
  for (let i = 0; i < list.length; i++) {
    if (list[i][groupFields] == tempGroupValue && obj[sortFields] <= list[i][sortFields]) {
      list.splice(i, 0, obj);
      return
    }
  }
  if (tempLength == list.length) {
    list.push(obj)
  }
}

const sortByFields = (sortFields, list) => {
  return list.sort((a, b) => {
    if (a[sortFields] < b[sortFields]) {
      return -1
    }
    if (a[sortFields] > b[sortFields]) {
      return 1
    }
    return 0
  })
};

const createComprisonFunction = (propertyName) => {
  return function (object1, object2) {
    var value1 = object1[propertyName] * 1;
    var value2 = object2[propertyName] * 1;
    if (value1 < value2) {
      return -1;
    } else if (value1 > value2) {
      return 1;
    } else {
      return 0;
    }
  }
}

const showOperate = (operateTrigger) => {
  if (operateTrigger == 1) {
    return '启用';
  } else if (operateTrigger == undefined) {
    return '无';
  } else {
    return "停用"
  }
}
let transferScene = ref('');

const showChooseWorkDay = (str) => {
  let hstr = '';
  if (str) {
    let arr = str.split(',');
    arr.sort(function (a, b) {
      return a - b;   // 按照升序排列 
    });
    for (let i = 0; i < arr.length; i++) {
      str += '周' + showWeek(arr[i]) + ",";
    }
    hstr = hstr.slice(0, -1);
    hstr = '每' + hstr + '运行';
  }
  return hstr;
}

const showWeek = (str) => {
  if (str == 1) {
    return '一'
  } else if (str == 2) {
    return '二'
  } else if (str == 3) {
    return '三'
  } else if (str == 4) {
    return '四'
  } else if (str == 5) {
    return '五'
  } else if (str == 6) {
    return '六'
  } else if (str == 7) {
    return '日'
  }
}

const showLampgroup = (data) => {
  let list = [];
  let arr = [];
  if (data.gatewayType == 'PLC') {
    list = data.operateInfo;
    if (JSON.stringify(list) == "{}") {
      list = [];
    }
    if (list == undefined) {
      return false;
    }
    for (let i = 0; i < list.length; i++) {
      let st = list[i].split(',')[1];
      if (st == "FF") {
        st = "全部"
      }
      arr.push(st)
    }
    arr = Array.from(new Set(arr));
  } else {
    list = data.operateInfo;
    if (JSON.stringify(list) == "{}") {
      list = [];
    }
    if (list == undefined) {
      return false;
    }
    for (let i = 0; i < list.length; i++) {
      arr.push(list[i].area + '区' + list[i].address + '组')
    }
    arr = Array.from(new Set(arr));
  }
  let str = '';
  for (let i = 0; i < arr.length; i++) {
    str += arr[i] + '<br/>'
  }
  return str;
}

const showOper = (strt) => {
  if (strt == undefined) {
    return '';
  } else if (typeof strt === 'string') {
    return JSON.parse(strt);
  } else {
    return strt;
  }
}

const showProfile = (data) => {
  let str = '无';
  if (data.gatewayType != 'PLC') {
    str = data.operateInfo[0] && data.operateInfo[0].params;
  }
  return str;
}

const del = (data) => {
  ElMessageBox.confirm(i18n.language === 'zh-cn' ? "确认删除？" : 'Confirm deletion?', i18n.language === 'zh-cn' ? "提示" : 'prompt').then(() => {
    $.post($httpUrl + "/deviceTimingRule/deleteTimingRule", { id: data.id }, function (res) {
      if (res.code == 200) {
        layer.msg(i18n.language === 'zh-cn' ? "删除成功" : 'Successfully deleted');
        getTableData(data.queryForm)
      } else {
        layer.msg(res.msg);
      }
    })
  })
}

const arrDistinctByProp = (arr, prop) => {
  let obj = {};
  return arr.reduce(function (preValue, item) {
    obj[item[prop]] ? '' : obj[item[prop]] = true && preValue.push(item);
    return preValue
  }, [])
}

let group_1 = ref([]);
let district_1 = ref('');
let deviceAreaAllList = ref([]);

const getDeviceAreaAllList = () => {
  var formData = new FormData(); // 当前为空
  formData.append('deviceFid', pid.value);
  $axios.post('/operationDevice/deviceAreaAllList', formData).then(res => {
    let newArr = arrDistinctByProp(res.data.data, 'area_code');
    deviceAreaAllList.value = newArr;
    deviceAreaAllList.value = deviceAreaAllList.value.sort((a, b) => {
      return a.area_code - b.area_code;
    })
  }).catch(err => {
  })
}

let curData = null;
const edit = (data) => {
  group_1.value = [];
  pubGatewayType.value = data.gatewayType == "PLC" ? 0 : 1;
  curData = data;
  if (curData) {
    let row = JSON.parse(JSON.stringify(curData));
    if (!(row.chooseWorkDay instanceof Array)) {
      row.chooseWorkDay = row.chooseWorkDay.split(',');
    }
    scenModel.data = row;
  }
  pid.value = data.deviceFid;
  getDeviceAreaAllList();
  getDeviceAliasAllList();
  form.render();
  chooseWorkDay.value = [];
  mainIndex = layer.open({
    type: 1,
    title: i18n.fy.编辑 + i18n.fy.定时任务,
    content: $("#saveOrUpdateDiv99"),
    area: ['37%', '55%'],
    maxmin: true,
    success: function (index) {
      $("#ruleTitle").val(data.ruleTitle);
      $("#startTime").val(data.startTime);
      $("#stopTime").val(data.stopTime);
      $("#hasPeopleBrightness").val(data.hasPeopleBrightness);
      if (data.enableState == 1) {
        $('#status_0').attr('checked', true)
      } else {                                              //radio单选框编辑回显
        $('#status_1').attr('checked', true)
      }
      if (data.operateTrigger == 1) {
        $('#status_3').attr('checked', true)
      } else {                                              //radio单选框编辑回显
        $('#status_4').attr('checked', true)
      }
      chooseWorkDay.value = data.chooseWorkDay.split(',').map((item) => {
        return item * 1;
      })
      let list = [];
      let arr = [];
      if (data.gatewayType == 'PLC') {
        list = data.operateInfo;
        for (let i = 0; i < list.length; i++) {
          arr.push(list[i].split(',')[1])
        }
        arr = Array.from(new Set(arr));
      } else {
        let obj = JSON.parse(JSON.stringify(data.operateInfo));
        scenModel.data.operateInfo = obj;
        for (let i = 0; i < obj.length; i++) {
          district_1.value = obj[i].area;
          group_1.value.push(obj[i].address);
        }
        console.log(district_1.value);
        console.log(group_1.value)
      }
      customName.value = arr;
      transferScene.value = data.operateInfo[0].params;
      form.render();
      if (pubGatewayType.value == 1) {
        url = $httpUrl + "/deviceTimingRule/addMeshTimingRule";
      } else {
        url = $httpUrl + "/deviceTimingRule/addTimingRule";
      }
    }
  });
}
let scenModel = reactive({
  data: {
    chooseWorkDay: '1,2,3,4,5,6,7'
  }
})
let optionsGroup = ref([]);
let customName = ref('');
const getDeviceAliasAllList = () => {
  if (!pid.value) {
    return false;
  }
  $.post($httpUrl + "/operationDevice/deviceGroupAllList", {
    deviceFid: pid.value
  }, function (res) {
    optionsGroup.value = res.data.filter((item) => {
      return item.group_name
    });

    optionsGroup.value.push({
      group_name: "FF",
      name: '全部'
    })
    optionsGroup.value = uniqueFunc(optionsGroup.value, "group_name");
    optionsGroup.value.sort((a, b) => {
      return a.group_name - b.group_name;
    })
  })
}
const uniqueFunc = (arr, uniId) => {
  const res = new Map();
  return arr.filter((item) => !res.has(item[uniId]) && res.set(item[uniId], 1));
}
const sceneTableData = ref([]);
const doSubmit = () => {
  if ($("#ruleTitle").val() == '') {
    layer.msg("任务名称不能为空");
    return false;
  } else if ($("#startTime").val() == '') {
    layer.msg("请选择开始时间");
    return false;
  } else if ($("#hasPeopleBrightness").val() == '' && pubGatewayType.value == 0) {
    layer.msg("请选择执行亮度");
    return false;
  } else if (chooseWorkDay.value.length == 0) {
    layer.msg("请选择运行周期");
    return false;
  } else if (customName.value == '') {
  }
  if (pubGatewayType.value == 1 && scenModel.data.operateInfo.length == 0) {
    layer.msg("请选择灯组");
    return false;
  }
  if (pubGatewayType.value == 1 && transferScene.value == '') {
    layer.msg("请选择调用情景");
    return false;
  }
  if (pubGatewayType.value == 1) {
    for (let i = 0; i < scenModel.data.operateInfo.length; i++) {
      scenModel.data.operateInfo[i].params = transferScene.value;
    }
    let obj = {
      "deviceFid": pid.value,
      "deviceTimingRule": {
        "chooseWorkDay": chooseWorkDay.value.toString(),
        "startTime": $("#startTime").val(),
        "operateInfo": JSON.stringify(scenModel.data.operateInfo),
        "ruleTitle": $("#ruleTitle").val(),
        "enableState": $('input[name="enableState"]:checked').val(),
        "productId": pid.value
      }
    };
    let urls = '';
    if (curData == null) {
      urls = '/deviceTimingRule/addMeshTimingRule';
    } else {
      obj = {
        "deviceFid": pid.value,
        "deviceTimingRule": {
          ...curData,
          "chooseWorkDay": chooseWorkDay.value.toString(),
          "startTime": $("#startTime").val(),
          "operateInfo": JSON.stringify(scenModel.data.operateInfo),
          "ruleTitle": $("#ruleTitle").val(),
          "enableState": $('input[name="enableState"]:checked').val(),
          "productId": pid.value
        }
      };
      urls = '/deviceTimingRule/update';
    }
    $axios.post(urls, obj).then(res => {
      if (res.data.code === 200) {
        if (curData == null) {
          layer.close(mainIndex);
          layer.msg("新增成功！");
        } else {
          layer.close(mainIndex);
          layer.msg("编辑成功！");
        }
        getTableData({ deviceFid: pid.value })
      }
    }).catch(err => { })
  } else {
    //序列化表单数据
    var params = $("#dataFrm67").serialize();
    if ((curData == null)) {
      params = params.replace("stopTime=", "stopTime=" + '23:59');
    }
    let deviceFid = '';
    if (curData) {
      deviceFid = curData.deviceFid;
    } else {
      deviceFid = pid.value;
    }
    params = params.replace("deviceFid=", "deviceFid=" + deviceFid);
    params = params + '&chooseWorkDay=' + chooseWorkDay.value.toString();
    params = params + '&groupName=' + customName.value.toString();
    if (curData) {
      params = params + '&id=' + curData.id;
    }
    console.log("url" + url);
    if (pubGatewayType.value == 1) {
      url = $httpUrl + "/deviceTimingRule/addMeshTimingRule";
    } else {
      url = $httpUrl + "/deviceTimingRule/addTimingRule";
    }
    $.ajax({
      url: url,
      data: params,
      dataType: 'json',
      type: 'post',
      success: function (res) {
        if (res.code == 200) {
          layer.close(mainIndex);
          if (curData == null) {
            layer.msg("新增成功！");
          } else {
            layer.msg("编辑成功！");
          }
          getTableData({ deviceFid: pid.value })
        } else {
          layer.msg(res.msg);
        }
      }, error: function (data) {
        layer.msg("系统错误");
      }
    })
  }
}
const getHeight = () => {
  return (window.innerHeight - 240) + 'px';
}
const showType = (type) => {
  if (type == -1) return "系统";
  if (type == 0) return "云平台";
  if (type == 1) return "云产品";
  if (type == 2) return "云设备";
}

let typeOptions = ref([
  { value: "400", label: '新增整区' },
  { value: "200", label: '新增整组' },
  { value: "100", label: '新增单号' },
  { value: "300", label: '新增标签' },
  { value: "10", label: '自由新增' },
]);
let typeOpt = ref('400');

let gatewayList = ref([]);
const getGateway = (params) => {
  gatewayList.value = params;
}
let identity_1 = ref('');
let lampVisible = ref(false);
let timeLamp = null;
const addingLamp = () => {
  lampVisible.value = true;
  getList3({ deviceFid: pid.value })
}
const enterOs = () => {
  let address = '';
  if (typeOpt.value == '400') {
    address = district_1.value;
    if (district_1.value === '') {
      ElMessage.error('区组号信息不能为空')
      return
    } else {
      tags.value.push(district_1.value + '区')
      scenModel.data.operateInfo.push({
        "code": typeOpt.value,
        "deviceName": pid.value,
        "area": district_1.value,
        "address": address,
        "action": "callScene",
        "params": transferScene.value,
        "identity": identity_1.value
      });
      scenModel.data.operateInfo = deleteRepeat(scenModel.data.operateInfo);
      lampVisible.value = false;

    }
  } else if (typeOpt.value == '200') {
    address = group_1.value;
    if (district_1.value === '' && group_1.value.length == 0) {
      ElMessage.error('区组号信息不能为空')
      return
    } else if (district_1.value !== '' && group_1.value.length != 0) {
      for (let i = 0; i < group_1.value.length; i++) {
        tags.value.push(district_1.value + '区' + group_1.value[i] + "组")
        scenModel.data.operateInfo.push({
          "code": typeOpt.value,
          "deviceName": pid.value,
          "area": district_1.value,
          "address": group_1.value[i],
          "action": "callScene",
          "params": transferScene.value,
          "identity": identity_1.value
        });
      }
      scenModel.data.operateInfo = deleteRepeat(scenModel.data.operateInfo);
      lampVisible.value = false;
    }
  } else if (typeOpt.value == '100') {
    address = num_1.value;
    if (district_1.value === '' && num_1.value === '') {
      ElMessage.error('区组号信息不能为空')
      return
    } else if (district_1.value !== '' && num_1.value != '') {
      tags.value.push(district_1.value + '区' + num_1.value + '号')
      scenModel.data.operateInfo.push({
        "code": typeOpt.value,
        "deviceName": pid.value,
        "area": district_1.value,
        "address": address,
        "action": "callScene",
        "params": transferScene.value,
        "identity": identity_1.value
      });
      scenModel.data.operateInfo = deleteRepeat(scenModel.data.operateInfo);
      lampVisible.value = false;
    }
  } else if (typeOpt.value == '300') {
    address = num_tag.value;
    if (district_1.value === '' && num_tag.value === '') {
      ElMessage.error('区组标签信息不能为空')
      return
    } else if (district_1.value !== '' && num_tag.value !== '') {
      tags.value.push(district_1.value + '区' + num_tag.value + '标签')
      scenModel.data.operateInfo.push({
        "code": typeOpt.value,
        "deviceName": pid.value,
        "area": district_1.value,
        "address": address,
        "action": "callScene",
        "params": transferScene.value,
        "identity": identity_1.value
      });
      scenModel.data.operateInfo = deleteRepeat(scenModel.data.operateInfo);
      lampVisible.value = false;
    }
  } else {
    if (multipleSelection3.value.length == 0) {
      ElMessage.error('请选择至少一个灯')
      return;
    }
    for (let i = 0; i < multipleSelection3.value.length; i++) {
      scenModel.data.operateInfo.push({
        "code": typeOpt.value == 10 ? 100 : typeOpt.value,
        "deviceName": multipleSelection3.value[i].deviceFid,
        "area": multipleSelection3.value[i].areaCode,
        "address": multipleSelection3.value[i].deviceIndex,
        "action": "callScene",
        "params": transferScene.value,
        "identity": ''
      });
    }
    scenModel.data.operateInfo = deleteRepeat(scenModel.data.operateInfo);
    lampVisible.value = false;
    multipleSelection3.value = [];
    multipleSelection3Tab.value.clearSelection();
  }
}
const handleSelectionChange3 = (val) => {
  multipleSelection3.value = val
}
const deleteTag = (i) => {
  scenModel.data.operateInfo.splice(i, 1);
}
const deleteRepeat = (arr) => {
  arr = arr.map(item => {
    return JSON.stringify(item);
  });
  return Array.from(new Set(arr)).map(item => {
    return JSON.parse(item);
  });
}
const multipleTableRef = ref()
const multipleTableRef_3 = ref()
const multipleSelection = ref([])
const multipleSelection2 = ref([])
const multipleSelection3 = ref([])
const multipleSelection_3 = ref([])
//全局列表
var tableIns;
//后台设定开灯值
var lightOnNum = 40;
//后台设定关灯值
var lightOffNum = 0;
//全局弹出
var mainIndex;
let total = 0;
var $ = '';
var layer = '';
var form = '';
var table = '';
var dropdown = '';
var sdTable = '';
var slider = '';
var slider1 = '';
var slider2 = '';
let _sensitivity = 0;
var secIndex = '';
var lightNum = 0;
var url = '';
var laydate = '';
var laydate2 = '';

onMounted(() => {
  layui.extend({
  }).use(['jquery', 'layer', 'form', 'table', 'slider', 'laydate', 'dropdown'], function () {
    $ = layui.jquery;
    layer = layui.layer;
    form = layui.form;
    table = layui.table;
    dropdown = layui.dropdown;
    sdTable = layui.table;
    slider = layui.slider;
    slider1 = layui.slider;
    slider2 = layui.slider;
    laydate = layui.laydate;
    laydate2 = layui.laydate;
    _sensitivity = 0;
    //第二弹出
    secIndex = '';
    //渲染滑块
    var lightNum = 0;
    slider.render({
      elem: '#slideTest1'  //绑定元素
      , input: true //输入框
      , min: 0
      , max: 100
      , change: function (value) {
        lightNum = value;
      }
    });
    var lightNum2 = 0;
    slider2.render({
      elem: '#slideTest2'  //绑定元素
      , input: true //输入框
      , min: 0
      , max: 100
      , change: function (value) {
        lightNum2 = value;
      }
    });
    $("#hasPeopleBrightness").click(function () {
      secIndex = layer.open({
        type: 1,
        title: '有人时亮度:',
        content: $("#slideDiv"),
        area: ['40%', '37%'],
        btnAlign: 'c',
        btn: ['<div class="layui-icon layui-icon-release">确定</div>', '<div class="layui-icon layui-icon-close">取消</div>'],
        yes: function (index, layero) {
          layer.close(secIndex);
          $("#hasPeopleBrightness").val(lightNum);
        }
      })
    })
    $("#noPeopleBrightness").click(function () {
      secIndex = layer.open({
        type: 1,
        title: '无人时亮度:',
        content: $("#slideDiv2"),
        area: ['40%', '37%'],
        btnAlign: 'c',
        btn: ['<div class="layui-icon layui-icon-release">确定</div>', '<div class="layui-icon layui-icon-close">取消</div>'],
        yes: function (index, layero) {
          if (lightNum2 > lightNum) {
            layer.msg("无人时亮度不能大于有人时亮度！");
          } else {
            layer.close(secIndex);
            $("#noPeopleBrightness").val(lightNum2);
          }
        }
      })
    })
    //执行一个laydate实例
    laydate.render({
      elem: '#startTime',//指定元素
      type: 'time',
      format: 'HH:mm',
      trigger: 'click',
      btns: ['clear', 'confirm'],
      ready: formatminutes
    });
    //执行一个laydate实例
    laydate2.render({
      elem: '#stopTime',//指定元素
      type: 'time',
      format: 'HH:mm',
      trigger: 'click',
      btns: ['clear', 'confirm'],
      ready: formatminutes
    });

    //去除日期控件秒
    function formatminutes (date) {
      var aa = $(".laydate-time-list li ol")[1];
      var showtime = $($(".laydate-time-list li ol")[1]).find("li");
      for (var i = 0; i < showtime.length; i++) {
        var t00 = showtime[i].innerText;
        if (t00 != "00" && t00 != "10" && t00 != "20" && t00 != "30" && t00 != "40" && t00 != "50") {
        }
      }
      $($(".laydate-time-list li ol")[2]).find("li").remove(); //清空秒
    }
    form.on("submit(doSubmit)", function (obj) {
      var startTime = $("#startTime").val();
      var stopTime = $("#stopTime").val();
      //序列化表单数据
      var params = $("#dataFrm67").serialize();
      $.ajax({
        url: url,
        data: params,
        dataType: 'json',
        type: "post",
        success: function (res) {
          if (res.code == 200) {
            layer.close(mainIndex);
            layer.msg("操作成功！");
            var deviceFid = $(".deviceFid").val();
            tableIns.reload({
              url: "deviceTimingRule/findAllDeviceTimingRule?deviceFid=" + deviceFid
            })
          } else {
            layer.msg(res.msg);
          }
        }, error: function (data) {
          layer.msg("系统错误");
        }
      })
      return false;
    });
  })
  getTableData({})
})
</script>

<style lang="scss">
.TimingRuleList {
  .enable-state-cls-0 {
    color: red;
    font-weight: bold;
  }

  .enable-state-cls-1 {
    color: #fff;
    font-weight: bold;
  }

  .q-y-cls {
    background-color: #59a420;
  }

  .t-y-cls {
    background-color: #787878;
  }

}
</style>

<style>
.dialog-footer {
  text-align: center;
  width: 100%;
  display: block;
}

.el-dialog__body .top .el-row>div {
  display: flex;
  align-items: center;
}

.top .el-row>div>span {
  display: inline-block;
  width: 100px;
  text-align: right;
  padding-right: 10px;
}

.el-dialog__body .top .el-row>div>span {
  width: auto;
  white-space: nowrap;
  padding: 0 5px;
}

body.toDeviceTimingRuleManager .altconp {
  text-align: left;
  padding-left: 0;
}

.radiocont .layui-form-radio {
  display: none;
}

.layui-layer-shade {
  z-index: 0 !important;
}

.toDeviceTimingRuleManager .layui-layer-page {
  z-index: 779 !important;
}

.sceneTableData .cell {
  color: #fff;
}

.sceneTableData td .cell {
  color: #000;
}

.sceneTableData th {
  background: var(--el-color-primary) !important;
}

.altcon {
  width: 120px;
  height: 36px;
  background-color: #ecf0f8;
  border-radius: 6px;
  text-align: center;
  line-height: 36px;
  margin-left: 10px;
  font-size: 14px;
  color: #1e62da;
  width: fit-content;
  padding: 0px 6px;
  margin-bottom: 10px;
  display: inline-block;
  cursor: pointer;
}

body.toDeviceTimingRuleManager .operateInfo {
  text-align: left;
  padding-left: 20px;
  box-sizing: border-box;
  font-weight: normal;
}

body.toDeviceTimingRuleManager .operateInfo span {
  font-weight: normal;
}

#saveOrUpdateDiv99 .layui-form-item .layui-form-checkbox {
  display: none;
}
</style>